import { getRepository } from 'typeorm';
import { EnterpriseEntity } from '../entity/enterprise.entity';
import { encrypt } from '../utils/crypto';
import { simpleUUID } from '../utils/uuid';

const enterpriseRepository = getRepository(EnterpriseEntity);

export async function login(entity: EnterpriseEntity) {
  return await enterpriseRepository.findOne({
    username: entity.username,
    password: encrypt(entity.password)
  });
}

export async function register(entity: EnterpriseEntity) {
  const result = await enterpriseRepository.findOne({
    username: entity.username
  });
  if (result) return -1;
  entity.id = simpleUUID();
  entity.password = encrypt(entity.password);
  const { raw } = await enterpriseRepository.insert(entity);
  return raw.affectedRows;
}

export async function update(id: string, enterprise: EnterpriseEntity) {
  enterprise.password = encrypt(enterprise.password);
  const { affected } = await enterpriseRepository.update(id, enterprise);
  return affected;
}

export async function select(id: string) {
  return await enterpriseRepository.findOne(id);
}
